import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  state: {
    isAuthenticated: !!localStorage.getItem('token'),
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || '',
    clients: [],
    cargos: [],
    portAreas: [],
    storageRecords: [],
    feeRules: [],
    storageFees: [],
    invoices: []
  },
  
  mutations: {
    // 认证相关
    setAuth(state, { token, user }) {
      state.isAuthenticated = true
      state.token = token
      state.user = user
      
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      
      // 添加调试信息
      console.log('认证成功，令牌已保存', { token, user })
    },
    
    logout(state) {
      state.isAuthenticated = false
      state.token = ''
      state.user = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      // 添加调试信息
      console.log('已登出，令牌已清除')
    },
    
    // 数据管理
    setClients(state, clients) {
      state.clients = clients
    },
    
    setCargos(state, cargos) {
      state.cargos = cargos
    },
    
    setPortAreas(state, portAreas) {
      state.portAreas = portAreas
    },
    
    setStorageRecords(state, records) {
      state.storageRecords = records
    },
    
    setFeeRules(state, rules) {
      state.feeRules = rules
    },
    
    setStorageFees(state, fees) {
      state.storageFees = fees
    },
    
    setInvoices(state, invoices) {
      state.invoices = invoices
    }
  },
  
  actions: {
    // 认证相关
    async login({ commit }, credentials) {
      try {
        const response = await axios.post('auth/login', credentials)
        const { token, user } = response.data.data
        commit('setAuth', { token, user })
        
        // 添加调试信息
        console.log('登录成功，API响应:', response.data)
        // 测试令牌是否正确保存
        console.log('存储在localStorage中的令牌:', localStorage.getItem('token'))
        
        return response
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    async register({ commit }, userData) {
      try {
        const response = await axios.post('auth/register', userData)
        const { token, user } = response.data.data
        commit('setAuth', { token, user })
        
        // 添加调试信息
        console.log('注册成功，API响应:', response.data)
        
        return response
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },
    
    logout({ commit }) {
      commit('logout')
    },
    
    // 客户管理
    async fetchClients({ commit }) {
      try {
        console.log('正在获取客户数据...')
        console.log('当前令牌:', localStorage.getItem('token'))
        
        const response = await axios.get('clients')
        commit('setClients', response.data.data)
        
        console.log('获取客户数据成功:', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取客户数据失败:', error)
        
        // 详细输出错误信息
        if (error.response) {
          console.error('错误状态码:', error.response.status)
          console.error('错误数据:', error.response.data)
          console.error('响应头:', error.response.headers)
        }
        
        throw error
      }
    },
    
    // 货物管理
    async fetchCargos({ commit }) {
      try {
        const response = await axios.get('cargos')
        commit('setCargos', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取货物数据失败:', error)
        throw error
      }
    },
    
    // 港口区域
    async fetchPortAreas({ commit }) {
      try {
        const response = await axios.get('port-areas')
        commit('setPortAreas', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取港口区域数据失败:', error)
        throw error
      }
    },
    
    // 仓储记录
    async fetchStorageRecords({ commit }) {
      try {
        const response = await axios.get('storage-records')
        commit('setStorageRecords', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取仓储记录数据失败:', error)
        throw error
      }
    },
    
    // 费用规则
    async fetchFeeRules({ commit }) {
      try {
        const response = await axios.get('fee-rules')
        commit('setFeeRules', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取费用规则数据失败:', error)
        throw error
      }
    },
    
    // 仓储费用
    async fetchStorageFees({ commit }) {
      try {
        const response = await axios.get('storage-fees')
        // 转换状态：将"已开票"状态显示为"已支付"
        const transformedFees = response.data.data.map(fee => {
          if (fee.paymentStatus === '已开票') {
            fee = {...fee, displayStatus: '已支付'}
          } else {
            fee = {...fee, displayStatus: fee.paymentStatus}
          }
          return fee
        })
        commit('setStorageFees', transformedFees)
        return transformedFees
      } catch (error) {
        console.error('获取仓储费用数据失败:', error)
        throw error
      }
    },
    
    // 获取未支付费用
    async fetchUnpaidFees({ dispatch }) {
      try {
        const fees = await dispatch('fetchStorageFees')
        // 过滤出未支付的费用
        return fees.filter(fee => fee.paymentStatus === '未支付')
                  .sort((a, b) => new Date(b.calculationDate) - new Date(a.calculationDate))
                  .slice(0, 5) // 只取前5条
      } catch (error) {
        console.error('获取未支付费用失败:', error)
        return []
      }
    },
    
    // 发票管理
    async fetchInvoices({ commit }) {
      try {
        const response = await axios.get('invoices')
        commit('setInvoices', response.data.data)
        return response.data.data
      } catch (error) {
        console.error('获取发票数据失败:', error)
        throw error
      }
    },
    
    // 获取发票详情
    async fetchInvoiceDetail(_, invoiceId) {
      try {
        console.log('store.fetchInvoiceDetail - 获取发票详情，ID:', invoiceId)
        const url = `invoices/${invoiceId}`
        console.log('store.fetchInvoiceDetail - 请求URL:', url)
        const response = await axios.get(url)
        console.log('store.fetchInvoiceDetail - 获取发票详情成功:', response.data)
        return response.data.data
      } catch (error) {
        console.error('store.fetchInvoiceDetail - 获取发票详情失败:', error)
        throw error
      }
    }
  },
  
  getters: {
    isAuthenticated: state => state.isAuthenticated,
    currentUser: state => state.user,
    token: state => state.token,
    clients: state => state.clients,
    cargos: state => state.cargos,
    portAreas: state => state.portAreas,
    storageRecords: state => state.storageRecords,
    feeRules: state => state.feeRules,
    storageFees: state => state.storageFees,
    invoices: state => state.invoices
  }
}) 